package com.ryl.yomall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.payment.config.AlipayConfig;
import com.ryl.yomall.payment.service.AlipayService;
import com.ryl.yomall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Date 18:47
 * @Author ryl
 */
@Controller
@RequestMapping("api/payment/alipay/")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentService paymentService;
    @GetMapping("submit/{orderId}")
    @ResponseBody
    public String submitAlipay(@PathVariable Long orderId){
        String aliPay="";
        try {
             aliPay = alipayService.createAliPay ( orderId );
        } catch (AlipayApiException e) {
            e.printStackTrace ( );
        }
        return aliPay;
    }
    @RequestMapping("callback/return")
    public String callBack() {
        // 同步回调给用户展示信息
        return "redirect:" + AlipayConfig.return_order_url;
    }
    @PostMapping("callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){

        boolean signVerified = false;//调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(
                    paramsMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            if(signVerified){
                // 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                if("TRADE_SUCCESS".equals ( paramsMap.get ( "trade_status" ) )){
                    paymentService.updatePaymentInfo(paramsMap);

                }
                System.out.println(paramsMap);
                return "success";
            }else{
                //  验签失败则记录异常日志，并在response中返回failure.
                System.out.println("验签失败");
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace ( );
        }

        return null;
    }


}
